using System.Collections.Generic;
using System.Text.Json;
using JlPay.Sdk.Core;
using JlPay.Sdk.Models;
using JlPay.Sdk.Services;

namespace JlPay.Sdk.Models.Ledger.BalanceSplit
{
    /// <summary>
    /// 余额分账查询响应
    /// </summary>
    public class BalanceSplitQueryResponse : StandardResponse, IComplexFieldHandler
    {
        /// <summary>
        /// 机构代码
        /// </summary>
        public string OrgCode { get; set; } = string.Empty;

        /// <summary>
        /// 外部订单号
        /// </summary>
        public string OutOrderNo { get; set; } = string.Empty;

        /// <summary>
        /// 订单号
        /// </summary>
        public string OrderNo { get; set; } = string.Empty;

        /// <summary>
        /// 分账总金额
        /// </summary>
        public string TotalAmount { get; set; } = string.Empty;

        /// <summary>
        /// 状态
        /// </summary>
        public string State { get; set; } = string.Empty;

        /// <summary>
        /// 分账接收方列表
        /// </summary>
        public List<Receiver> Receivers { get; set; } = new List<Receiver>();

        /// <summary>
        /// 处理复杂字段
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        public void HandleComplexField(string fieldName, object fieldValue)
        {
            if (fieldName == "receivers" && fieldValue is System.Text.Json.JsonElement jsonElement)
            {
                Receivers.Clear();
                
                if (jsonElement.ValueKind == System.Text.Json.JsonValueKind.Array)
                {
                    foreach (var element in jsonElement.EnumerateArray())
                    {
                        if (element.ValueKind == System.Text.Json.JsonValueKind.Object)
                        {
                            var receiverDict = new Dictionary<string, object>();
                            foreach (var property in element.EnumerateObject())
                            {
                                if (property.Value.ValueKind == System.Text.Json.JsonValueKind.String)
                                {
                                    receiverDict[property.Name] = property.Value.GetString() ?? "";
                                }
                                else if (property.Value.ValueKind == System.Text.Json.JsonValueKind.Number)
                                {
                                    receiverDict[property.Name] = property.Value.GetInt64().ToString();
                                }
                                else
                                {
                                    receiverDict[property.Name] = property.Value.GetRawText();
                                }
                            }
                            var receiver = new Receiver(receiverDict);
                            Receivers.Add(receiver);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 重写HandleResponse方法，手动处理receivers字段
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <param name="config">配置对象</param>
        public new void HandleResponse(string operationName, Config? config = null)
        {
            if (IsSuccess())
            {
                // 手动构建响应JSON，确保receivers字段正确序列化
                var responseData = new Dictionary<string, object>
                {
                    ["ret_code"] = RetCode ?? "",
                    ["ret_msg"] = RetMsg ?? "",
                    ["org_code"] = OrgCode,
                    ["out_order_no"] = OutOrderNo,
                    ["order_no"] = OrderNo,
                    ["total_amount"] = TotalAmount,
                    ["state"] = State,
                    ["receivers"] = Receivers.Select(r => r.ToDictionary()).ToList()
                };
                
                Console.WriteLine("响应报文：" + JsonSerializer.Serialize(responseData, new JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                }));
            }
            else
            {
                Console.WriteLine($"{operationName}失败: {RetCode} - {RetMsg}");
            }
        }
    }
} 